package com.gxc.oauth2.config.service;

import com.gxc.oauth2.repository.UserRepository;
import com.gxc.oauth2.entity.TbPermissionEntity;
import com.gxc.oauth2.entity.TbUserEntity;
import com.gxc.oauth2.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author GongXincheng
 * @since 2019-10-11 18:06
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private UserService userService;

    @Resource
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TbUserEntity user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("not't find user by username, entity is null");
        }

        // 获取权限.
        List<GrantedAuthority> authorityList = new ArrayList<>();
        List<TbPermissionEntity> permissionList = userService.getUserPermissionList(user.getId());
        for (TbPermissionEntity permissionEntity : permissionList) {
            authorityList.add(new SimpleGrantedAuthority(permissionEntity.getEnname()));
        }
        return new User(user.getUsername(), user.getPassword(), authorityList);
    }

}
